package server;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * User: tum0r
 * Package Name: server
 * Time: 2019-04-17 Wednesday 21:33:05
 */
public class NoticeServer extends BaseServer {
    public boolean recordNotice(String user, String title, String content, int priority) {
        LinkedList<LinkedHashMap<String, Object>> temp = sql.query("select uuid from user where username=?", new Object[]{user});
        if (temp.size() > 0) {
            String userID = temp.get(0).get("uuid").toString();
            SimpleDateFormat faomat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss (z X)");
            return sql.update("insert into notice values(?,?,?,?,?,?,?)", new Object[]{UUID.randomUUID().toString(), title, content, userID, faomat.format(new Date()), priority, 1}) == 1;
        }
        return false;
    }

    public JSONArray getNotice() {
        JSONArray result = new JSONArray();
        LinkedList<LinkedHashMap<String, Object>> temp = sql.query("select * from notice where state=1 order by priority desc, time desc", null);
        Iterator<LinkedHashMap<String, Object>> tempIterator = temp.iterator();
        LinkedHashMap<String, Object> item;
        Iterator<String> itemIterator;
        String key;
        JSONObject items;
        LinkedList<LinkedHashMap<String, Object>> userTemp;
        while (tempIterator.hasNext()) {
            item = tempIterator.next();
            itemIterator = item.keySet().iterator();
            items = new JSONObject();
            while (itemIterator.hasNext()) {
                key = itemIterator.next();
                items.put(key, item.get(key) == null ? "" : item.get(key));
            }
            String userID = items.getString("user_id");
            userTemp = sql.query("select username from user where uuid=?", new Object[]{userID});
            if (userTemp.size() > 0) {
                items.put("username", userTemp.get(0).get("username") == null ? "" : userTemp.get(0).get("username"));
                result.add(items);
            }
        }
        return result;
    }

    public boolean deleteNotice(String noticeID) {
        return sql.update("delete from notice where uuid=?", new Object[]{noticeID}) == 1;
    }
}
